import request from '@/utils/request';

/**
 * 获取全局字典版本
 * @returns
 */
export function getDictVersion() {
	return request({
		url: '/api/v1/common/dict_version',
		method: 'get'
	})
}

/**
 * 获取全局字典
 * @returns
 */
export function getDict() {
	return request({
		url: '/api/v1/common/dict',
		method: 'get'
	})
}

/**
 * 获取最新字段并缓存到浏览器
 */
export function getDistStore() {
	//判断字段版本是否最新版本
	let distData = localStorage.getItem("dictData");
	return new Promise((resolve, reject) => {
		if (distData === null) {
			getDict().then((response) => {
				//缓存数据
				localStorage.setItem("dictData", JSON.stringify(response.data.dict));
				//缓存版本
				localStorage.setItem("dictVersion", response.data.version);
				resolve('success')
			});
		} else {
			let distVersion = localStorage.getItem("dictVersion");
			if (distVersion === null) {
				getDict().then((response) => {
					//缓存数据
					localStorage.setItem("dictData", JSON.stringify(response.data.dict));
					//缓存版本
					localStorage.setItem("dictVersion", response.data.version);
					resolve('success')
				});
			} else {
				getDictVersion().then((response) => {
					if (response.data !== localStorage.getItem("dictVersion")) {
						getDict().then((response) => {
							//缓存数据
							localStorage.setItem("dictData", JSON.stringify(response.data.dict));
							//缓存版本
							localStorage.setItem("dictVersion", response.data.version);
							resolve('success')
						});
					} else {
						console.log("版本相同");
						resolve('success')
					}
				});
			}
		}
	})
}

export function getDicts(key: string) {
	let temp = localStorage.getItem("dictData")
	if (temp) {
	 let dict =	JSON.parse(temp) ||{};
	 if(key in dict)
	 return dict[key];
	else
	return new Array();
	} else {
		return new Array();
	}
}
